package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.constant.ChatMessageConstant;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.dto.chat.ConversationDto;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.entity.system.SysNotification;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import com.example.everying.service.system.SysNotificationService;
import com.example.everying.service.user.UserService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class NavigationRedDotMessageHandler implements MessageHandler {


    private static ChatConversationService chatConversationService;
    private static ChatMessagesService chatMessagesService;
    private static SysNotificationService sysNotificationService;
    private static UserService userService;

    @Autowired
    private void setService(ChatConversationService chatConversationService,
                            ChatMessagesService chatMessagesService,
                            SysNotificationService sysNotificationService,
                            UserService userService) {
        NavigationRedDotMessageHandler.chatConversationService = chatConversationService;
        NavigationRedDotMessageHandler.chatMessagesService = chatMessagesService;
        NavigationRedDotMessageHandler.sysNotificationService = sysNotificationService;
        NavigationRedDotMessageHandler.userService = userService;
    }

    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        log.info("收到导航红点信息");
        String userId = WebSocketChatService.getUserId(session);
        sendRedDot(userId);
    }

    @Async
    public void sendRedDot(String userId){
        List<ConversationDto> conversations = chatConversationService.getUserConversationsByRedDot(userId);
        JSONObject result = new JSONObject();
        result.put("type", "navigationRedDotMessage");
        AtomicInteger unreadCount = new AtomicInteger();
        conversations.forEach(conversation -> {
            if (conversation.getUnreadCount() > 0) {
                unreadCount.addAndGet(conversation.getUnreadCount());
            }
        });
        // 评论未读消息数
        int unreadCount2 = Math.toIntExact(chatMessagesService.count(new QueryWrapper<ChatMessagesEntity>().eq("to_user_id", userId).
                eq("msg_status", ChatMessageConstant.MESSAGE_STATUS_UNREAD).eq("messages_type", ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_COMMENT)));
        log.info("评论未读消息数: {}", unreadCount2);
        int num = unreadCount2 + unreadCount.get();
        // 通知未读数
        int num2 = Math.toIntExact(sysNotificationService.count(new QueryWrapper<SysNotification>().eq("recipient_id", userId).eq("msg_status", 2)));
        // 官方通知的消息
        int num3 = Math.toIntExact(userService.getUserById(userId).getNoticeUnreadCount() == null ? 0 : userService.getUserById(userId).getNoticeUnreadCount());
        result.put("redDotNum", num + num2+ num3);
        WebSocketChatService.sendMessageToUserId(userId, result.toJSONString());
    }
}
